﻿namespace Typps
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Web.Script.Serialization;
    using System.Web.UI.WebControls;

    /// <summary>
    /// This converter knows how to serialize following types :
    /// MediaFrameCollection and MediaFrameThumbnailCollection
    /// </summary>
    public static class MediaFrameJavaScriptConverter
    {
        #region Methods

        public static ArrayList Serialize(MediaFrameCollection mfc)
        {
            if (mfc == null)
                throw new ArgumentNullException("you need to provide a MediaFrameCollection");
            return AddToDictionary(mfc);
        }

        public static ArrayList Serialize(MediaFrameThumbnailCollection thumbnails)
        {
            if (thumbnails == null)
                throw new ArgumentNullException("you need to provide a MediaFrameThumbnailCollection");
            return AddToDictionary(thumbnails);
        }

        private static ArrayList AddToDictionary(object obj)
        {
            MediaFrameCollection mediaFrameList = obj as MediaFrameCollection;
            MediaFrameThumbnailCollection mediaFrameThumbnailList = obj as MediaFrameThumbnailCollection;
            ArrayList itemsList = new ArrayList();
            if (mediaFrameList != null)
            {
                foreach (MediaItem mi in mediaFrameList)
                {
                    Dictionary<string, object> itemsDict = new Dictionary<string, object>();
                    itemsDict.Add("url", mi.Url);
                    itemsDict.Add("title", mi.Title);
                    itemsDict.Add("value", mi.Value);
                    itemsDict.Add("preload", mi.Preload);
                    itemsList.Add(itemsDict);
                }
            }
            else if (mediaFrameThumbnailList != null)
            {
                foreach (MediaItemThumbnail mit in mediaFrameThumbnailList)
                {
                    Dictionary<string, object> itemsDict = new Dictionary<string, object>();
                    itemsDict.Add("clientId", mit.ClientID);
                    itemsDict.Add("value", mit.Value);
                    itemsList.Add(itemsDict);
                }
            }
            return itemsList;
        }

        #endregion Methods
    }
}